<template>
  <div class="base-chart">
    <div class="chart-content">
      <div ref="chartRef" class="chart-container"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'

interface Props {
  title: string
  data: {
    xAxis: string[]
    series: {
      name: string
      data: number[]
    }[]
  }
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  data: () => ({
    xAxis: [],
    series: []
  })
})

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  const option = {
    title: {
      text: props.title
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: props.data.xAxis
    },
    yAxis: {
      type: 'value'
    },
    series: props.data.series.map(item => ({
      name: item.name,
      type: 'line',
      data: item.data
    }))
  }
  
  chart.setOption(option)
}

onMounted(() => {
  initChart();
  window.addEventListener("resize", handleResize);
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
  }
  window.removeEventListener("resize", handleResize);
})

watch(() => props.data, () => {
  if (chart) {
    initChart()
  }
}, { deep: true })

const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};
</script>

<style scoped>
.base-chart {
  width: 100%;
  height: 100%;
  padding: 16px;
  box-sizing: border-box;
  background: white;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.chart-content {
  width: calc(100% - 32px);
  height: calc(100% - 32px);
  display: flex;
  flex-direction: column;
}

h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.chart-container {
  flex: 1;
  width: 100%;
  height: 100%;
  background: white;
}
</style> 